<template>
    <div class="page-wrap page-wrap-ql" ref="pageWrapRef" v-loading="loading">
        <require-status :detail="detailData" :stage="detailData.stage" :stageInfo="stageInfo" v-if="detailData.id" class="page-header-wrap">
            <a-page-header @back="handleBack">
                <template #subTitle>
                    <span v-if="detailData.requestSystem">{{ $filters.valToNameFilter('fromSystem', detailData.requestSystem) }}-</span>
                    <span class="header-no">{{ detailData.requestNumber }}</span>
                </template>
                <template #tags>
                    <h-status-tag :status="detailData.status" class="margin-l-8" />
                </template>
                <div class="header-title">
                    {{ detailData.requestName }}
                </div>
                <flexbox v-if="detailData.relateId" align="flex-start" class="margin-t-8">
                    <a-tag color="warning"> 已合并到 </a-tag>
                    <a @click="showDetail(relateInfo)">
                        {{ relateInfo.requestName }}
                    </a>
                </flexbox>
            </a-page-header>
            <template #stepExtra v-if="+detailData.stage >= 5 && +detailData.status > 1 && detailData.status !== '5'">
                <div class="extra-wrap">
                    <a-tooltip title="刷新当前阶段">
                        <ReloadOutlined @click="handleReload" />
                    </a-tooltip>
                </div>
            </template>
            <img src="@/assets/images/badge-task.png" style="position: absolute; top: 8px; right: -10px" />
        </require-status>
        <div v-if="detailData.id" class="page-cont">
            <!-- 1.必须是我创建的 2.状态为草稿或者待处理的 -->
            <create-require v-if="showCreateRequire" :detail="detailData" />
            <!-- 走正常详情 -->
            <flexbox align="flex-start" v-else>
                <div class="page-cont-left">
                    <template v-for="(item, index) of comps" :key="index">
                        <div v-if="item.show">
                            <a-divider style="margin: 0" v-if="index !== 0" />
                            <component
                                :ref="setCompsItemRef(item)"
                                :is="item.comName"
                                :detail="detailData"
                                :modelName="item.modelName"
                                :disabled="item.disabled"
                                @save="handleSave"
                                @success="getDetailData"
                                @init="init"
                            />
                        </div>
                    </template>
                </div>
                <div class="page-cont-right">
                    <require-process :detail="detailData" />
                    <require-user-info />
                </div>
            </flexbox>
        </div>

        <!-- <iframe
            id="lanhuIframe"
            frameborder="no"
            width="100%"
            height="400px"
            src="http://10.141.32.105/web/#/item/project/product?tid=44e52482-6c34-4a7a-9609-9b4211850c06&pid=c8c168ce-5120-4bc0-95b0-ff73088073d9&versionId=874fcfc5-e7e6-48d5-8ddc-ca6423fed99e&docId=1426e2f9-105e-435a-8b52-670f553d7ad7&docType=axure&pageId=2d2e1cbe2c814ed7a69d462b6837b9cd&image_id=1426e2f9-105e-435a-8b52-670f553d7ad7&parentId=7ada041e-96e0-4b63-8530-22df93406104"
        /> -->
    </div>
</template>

<script lang="ts">
import RequireStatus from '@/components/Content/RequireStatus/index.vue';
import FirstRequire from '@/views/taskRequire/taskDetail/components/FirstRequire.vue';
import TaskRecord from '@/views/taskRequire/taskDetail/components/HistoryRecord/task/index.vue';
import RequireAcceptInfo from '@/views/taskRequire/taskDetail/components/RequireAcceptInfo.vue';
import RequireAdminCheck from '@/views/taskRequire/taskDetail/components/RequireAdminCheck.vue';
import TaskRequireAnalyse from '@/views/taskRequire/taskDetail/components/TaskRequireAnalyse.vue';
import RequireDistributation from '@/views/taskRequire/taskDetail/components/RequireDistribution.vue';
import RequireList from '@/views/taskRequire/taskDetail/components/RequireList.vue';
import RequireUserInfo from '@/views/taskRequire/taskDetail/components/RequireUserInfo.vue';
import RequireProcess from '@/views/taskRequire/taskDetail/components/RequireProcess.vue';
import CreateRequire from '@/views/taskRequire/taskDetail/components/CreateRequire.vue';
import RequireFollow from '@/views/taskRequire/taskDetail/components/RequireFollow/index.vue';
import { getViewportOffset } from '@/utils/dom';
import { HStatusTag } from '@/components';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { allComps } from './config/comps';
import { isNotEmpty } from '@/utils/is';
import api from '@/api';
import store from '@/store';
import { message } from 'ant-design-vue';
import { FileItem } from '@/types';
import { defineComponent, ref, unref, reactive, toRefs, computed, getCurrentInstance, nextTick } from 'vue';
export default defineComponent({
    name: 'SystemDetail',
    components: {
        RequireStatus,
        FirstRequire,
        RequireAcceptInfo,
        RequireAdminCheck,
        TaskRecord,
        TaskRequireAnalyse,
        RequireDistributation,
        RequireList,
        RequireUserInfo,
        RequireProcess,
        CreateRequire,
        RequireFollow,
        ReloadOutlined,
        HStatusTag
    },
    setup() {
        const { route, router, handleBack } = useRouterApi({
            backQuery: {
                path: '/taskRequire/myRequire'
            }
        });
        const instance: any = getCurrentInstance();
        const pageWrapRef: any = ref<any>();
        const compsItemRefs: any = reactive({});
        const setCompsItemRef = (item) => (el) => {
            compsItemRefs[`${item.comName}`] = el;
        };
        const state = reactive<any>({
            comps: [],
            allCanEditComps: [], // 所有可编辑模块
            form: {}, //存放所有表单信息
            relateInfo: {},
            detailData: {
                stage: '1',
                status: '1'
            },
            loading: false,
            stageInfo: {}
        });
        const showCreateRequire = computed(() => {
            // 如果是草稿
            if (state.detailData.status === '4') {
                return store.getters.userInfo.employeeDTO.empId === state.detailData.createUserEmpId;
            }
            // 如果是已拒绝
            else if (state.detailData.status === '8') {
                return isCreatedByMe.value;
            } else {
                return false;
            }
        });
        // 是否是我创建的
        const isCreatedByMe = computed(() => {
            return store.getters.userInfo.employeeDTO.empId === state.detailData.agentUser;
        });
        const isRuningOrNotParentRequire = computed(() => {
            if (isNotEmpty(state.detailData)) {
                const { status, relateRequest, sonRequestInfos } = state.detailData;
                if (relateRequest === 0) {
                    if (status === '1.1' || status === '1.2' || status === '2' || status === '3') {
                        if (sonRequestInfos && sonRequestInfos.length) {
                            return false;
                        } else {
                            return true;
                        }
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
            }
            return false;
        });
        const getDetailData = async () => {
            state.loading = true;
            const query = {
                id: route.query.id
            };
            const { success, moule, errorMsg } = await api.pmpRequestInfoModel.findById(query);
            if (success) {
                state.detailData = { ...moule };
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
            return success;
        };
        // 查询合并到哪条需求的信息
        const getRelateData = async (id: number) => {
            const query = {
                id
            };
            const { success, moule, errorMsg } = await api.pmpRequestInfoModel.findById(query);
            if (success) {
                state.relateInfo = { ...moule };
            } else {
                message.error(errorMsg);
            }
        };
        const handleReload = async () => {
            const { stage, id } = state.detailData;
            const query = {
                stage,
                id
            };
            const { success } = await api.pmpRequestInfoModel.updateStage(query);
            if (success) {
                message.success('已同步最新阶段');
                getDetailData();
            }
        };
        // 获取阶段状态;
        const getStageList = async () => {
            if (route.query.id) {
                const query = {
                    id: route.query.id
                };
                const { success, moule, errorMsg } = await api.historyModel.consumeTime(query);
                if (success) {
                    state.stageInfo = moule;
                } else {
                    message.error(errorMsg);
                }
            }
        };
        const initComps = () => {
            const type: number = state.detailData.isRequireAnalyse === '是' ? 0 : 1;
            state.comps = allComps[type].map((item) => ({
                show: checkIsShow(item),
                disabled: checkIsDisabled(item),
                comName: item.comName,
                modelName: item.modelName
            }));
            console.log(state.comps);
            handleScrollToCom();
        };

        // 检测模块是否显示
        const checkIsShow = (info) => {
            const { roles, stages } = info.permission;
            const { stage, isSplit, relateId } = state.detailData;
            if (relateId) {
                if (info.modelName !== '需求初审') {
                    return false;
                }
            }
            // 系统分析为否，不走需求分发
            if (info.modelName === '需求分发') {
                if (isSplit === '否') {
                    return false;
                }
            }
            if (info.modelName === '需求列表') {
                if (!unref(isRuningOrNotParentRequire)) {
                    return false;
                }
            }
            if (info.modelName === '需求跟进') {
                if (!unref(isRuningOrNotParentRequire)) {
                    return false;
                }
                // 自研流程不显示
                if (state.detailData.systemType === '2') {
                    return false;
                }
            }
            if (roles.length) {
                return store.getters.userInfo.roles.some(() => {
                    const res = state.detailData.agentUser && state.detailData.agentUser.includes(store.getters.userInfo.employeeDTO.empId);
                    return res;
                });
            } else {
                return stages.includes(stage);
            }
        };
        // 检测模块是否可编辑
        const checkIsDisabled = (info) => {
            let { stage, status, isRequireAnalyse, agentUser, responsibleEmpId, relateId } = state.detailData;
            agentUser = agentUser || '';
            const { empId } = store.getters.userInfo.employeeDTO;
            // 已合并不可编辑
            if (relateId) {
                return true;
            }
            // 状态为进行中
            if (status === '2') {
                if (info.comName !== 'RequireDistributation' && isRequireAnalyse !== '否' && stage !== '5') {
                    return true;
                }
            }
            //完成不可编辑
            if (status === '3' || status === '5' || status === '8') {
                return true;
            }
            // 根据角色和状态判断模块是否可编辑
            const { comName, edits } = info;
            if (edits.length) {
                return !edits.some((item) => {
                    const { roles, stages } = item;
                    return store.getters.userInfo.roles.some((item) => {
                        let res = false;
                        // 需求设计阶段进行特殊判断，必须是该系统负责人才能操作
                        if (stage === '5') {
                            if (comName === 'RequireDistributation' && responsibleEmpId) {
                                res = responsibleEmpId.includes(empId) && stages.includes(stage);
                            } else if (comName === 'RequireList') {
                                res = status === '2' && roles.includes(item) && agentUser.includes(empId) && stages.includes(stage);
                            } else {
                                res = roles.includes(item) && agentUser.includes(empId) && stages.includes(stage);
                            }
                        } else {
                            res = (roles.includes(item) || agentUser.includes(empId)) && stages.includes(stage);
                        }
                        if (res) {
                            state.allCanEditComps.push(comName);
                        }
                        return res;
                    });
                });
            } else {
                return true;
            }
        };
        // 检测是否填入
        const validateAllForm = async () => {
            let res = false;
            let files: FileItem[] = [];
            for (let i = 0; i < state.allCanEditComps.length; i++) {
                const name = state.allCanEditComps[i];
                const target = compsItemRefs[name];
                if (!target) {
                    break;
                }
                res = await target.validate();
                if (res) {
                    if (target.form) {
                        const { selfRequestFiles, ...query } = target.form;
                        if (selfRequestFiles) {
                            files = [...files, ...selfRequestFiles];
                        }
                        state.form = {
                            ...state.form,
                            ...query,
                            selfRequestFiles: files
                        };
                    }
                } else {
                    return res;
                }
            }
            return res;
        };
        const handleSave = async (type = 1) => {
            const res = await validateAllForm();
            if (res) {
                state.loading = true;
                const query = {
                    ...state.detailData,
                    ...state.form
                };
                let requestApi: any = null;
                switch (type) {
                    // 发起流程
                    case 1:
                        requestApi = api.pmpRequestInfoModel.save;
                        break;
                    // 暂存
                    case 2:
                        Reflect.deleteProperty(query, 'requestDesc');
                        requestApi = api.pmpRequestInfoModel.update;
                        break;
                }
                const { success, errorMsg } = await requestApi(query);
                if (success) {
                    message.success('操作成功');
                    // 拒绝需求
                    if (query.pass === '是' || type === 2) {
                        state.form = {};
                        init();
                    } else {
                        router.push({
                            path: '/taskRequire/myRequire'
                        });
                    }
                } else {
                    message.error(errorMsg);
                }
                state.loading = false;
            } else {
                message.error('请填写所有必填项');
            }
        };
        const showDetail = (info) => {
            const { id } = info;
            router.push({
                path: '/taskRequire/taskDetail',
                query: {
                    id
                }
            });
        };
        // 滚动到对应模块
        const handleScrollToCom = () => {
            // 没有编辑的模块无需进行滚动
            if (!state.allCanEditComps.length) {
                return;
            }
            nextTick(() => {
                let el: any = null;
                switch (state.detailData.stage) {
                    case '2':
                        el = compsItemRefs.RequireAcceptInfo.$el;
                        break;
                    case '4':
                        el = compsItemRefs.RequireDistributation.$el;
                        break;
                    case '5':
                        el = compsItemRefs.RequireAcceptInfo.$el;
                        break;
                }
                if (el) {
                    const info = getViewportOffset(el);
                    setTimeout(() => {
                        const dom = document.querySelector('.ant-layout-content');
                        if (document.querySelector('.page-header-wrap')) {
                            const headerHeight = (document.querySelector('.page-header-wrap') as any).offsetHeight;
                            dom?.scrollTo({
                                top: info.top - headerHeight - 64,
                                behavior: 'smooth'
                            });
                        }
                    }, 500);
                }
            });
        };
        const init = async () => {
            state.allCanEditComps = []; // 清空数据
            const res = await getDetailData();
            if (res) {
                const { relateId } = state.detailData;
                if (!relateId) {
                    getStageList();
                } else {
                    getRelateData(relateId);
                }
                initComps();
            }
            instance.proxy.$mitt.on('updateTaskDetail', () => {
                getDetailData();
            });
        };
        init();

        return {
            pageWrapRef,
            setCompsItemRef,
            ...toRefs(state),
            showCreateRequire,
            isCreatedByMe,
            handleSave,
            showDetail,
            handleBack,
            handleReload,
            getDetailData,
            init
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    position: relative;
    height: 100%;
    .page-header-wrap {
        position: sticky;
        top: 0;
        z-index: 9;
        border-bottom: 1px solid #f1f1f1;
        border-top: 1px solid #f1f1f1;
        &::before {
            content: '';
            position: absolute;
            width: 6px;
            height: 100%;
            background: #1e9493;
            top: 0;
            left: 0;
            z-index: 1;
        }
        .extra-wrap {
            position: absolute;
            right: 40px;
            bottom: 22px;
            color: #000;
            cursor: pointer;
        }
    }
    .header-title {
        font-size: 20px;
        color: @title-font-color;
        font-weight: bold;
    }
    .header-no {
        color: @primary-color;
    }
    .page-cont {
        margin-top: 24px;
        position: relative;
        background: #fff;

        &-left {
            width: 70%;
            border-right: 1px solid #e9e9e9;
        }
        &-right {
            width: 30%;
            height: 100%;
            .user-cont {
                font-size: 14px;
                dl {
                    display: flex;
                }
                .label {
                    width: 120px;
                    text-align: right;
                    overflow: hidden;
                    white-space: wrap;
                    margin-right: 8px;
                }
            }
        }
    }
}
</style>
